import pymongo

class MyMongo:
    #初始化时连接并进入数据库
    def __init__(self,db,collection):
        self.client = pymongo.MongoClient()
        self.db = self.client[db]
        self.collect = self.db[collection]
    #增
    def insert(self,data,flag = True):
        if flag:
            self.collect.insert_one(data)
        else:
            self.collect.insert_many(data)
    #查
    def find(self,flag = True):
        if flag:
            print(self.collect.find_one())
        else:
            for i in self.collect.find():
                print(i)
    #改
    def update(self,old_data,new_data,flag = True):
        if flag:
            self.collect.update_one(old_data, {'$set':new_data})
        else:
            self.collect.update_many(old_data, {'$set': new_data})
    #删
    def delete(self,data,flag = True):
        if flag:
            self.collect.delete_one(data)
        else:
            self.collect.delete_many(data)

if __name__ == '__main__':
    my = MyMongo('python','stu1')  #实例化
    print('--------------添加一条数据-------------')
    my.insert({'name':'甲'})
    my.find()
    print('--------------添加多条数据-------------')
    my.insert([
        {'name':'甲'},
        {'name':'乙'},
        {'name':'丙'},
        {'name':'丁'}
    ],flag=False)
    my.find(flag=False)
    print('--------------修改多条数据-------------')
    my.update({'name':'甲'},{'name':'戊'},flag=False)
    my.find(flag=False)
    print('----------------删除数据---------------')
    my.delete({'name':'丙'})
    my.find(flag=False)